package com.cjy.common.message;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.List;

/**
 * @author Cheng JiYe
 * @description:
 * @date 2020/11/10 10:24
 */
public class BaseResult<T> {
    /**
     * 启用分页
     *
     * @param pageNum  当前页码
     * @param pageSize 每页数量
     */
    private static void startPage(int pageNum, int pageSize) {
        if (pageNum < 1) {
            throw new RuntimeException("The page number must not be less than 0!");
        }
        if (pageSize < 1) {
            throw new RuntimeException("The number of rows per page must not be less than 0!");
        }
        PageHelper.startPage(pageNum, pageSize);
    }


    /**
     * 启用分页
     *
     * @param req 分页请求头
     */
    public static void startPage(RequestPageHead req) {
        if (req.isPage()) {
            startPage(req.getPageNum(), req.getPageSize());
        }
    }

    /**
     * 封装分页结果集
     *
     * @param <T>  实体类泛型
     * @param list 数据列表
     * @return 返回分页结果
     */
    public static <T> ResultPage<List<T>> packPageResult(List<T> list) {
        ResultPage<List<T>> result = new ResultPage<>();
        packPageInfo(result, list);
        result.setData(list);
        result.setCode(200);
        result.setMsg("操作成功");
        return result;
    }

    public static <T> AjaxResult<List<T>> packPageResult(PageInfo<T> pageInfo) {
        ResultPage<List<T>> result = new ResultPage<>();
        packPageInfo(result, pageInfo);
        result.setData(pageInfo.getList());
        result.setCode(200);
        result.setMsg("操作成功");
        return result;
    }


    /**
     * 封装分页的基础信息
     *
     * @param resultPage 返回对象
     * @param pageInfo
     */
    private static void packPageInfo(ResultPage<?> resultPage, PageInfo<?> pageInfo) {
        List<?> list = pageInfo.getList();
        //当前页码
        resultPage.setCurrentPage(pageInfo.getPageNum());
        //记录总数(总页数)
        resultPage.setPages(pageInfo.getPages());

        //每页显示总数
        resultPage.setPageSize(pageInfo.getPageSize());
        //记录总数
        resultPage.setTotal((int) pageInfo.getTotal());
    }

    /**
     * 封装分页的基础信息
     *
     * @param resultPage   返回对象
     * @param pageInfoList 待分页list
     */
    private static void packPageInfo(ResultPage<?> resultPage, List<?> pageInfoList) {
        PageInfo<?> pageInfo = new PageInfo<>(pageInfoList);
        List<?> list = pageInfo.getList();
        //当前页码
        resultPage.setCurrentPage(pageInfo.getPageNum());
        //记录总数(总页数)
        resultPage.setPages(pageInfo.getPages());

        //每页显示总数
        resultPage.setPageSize(pageInfo.getPageSize());
        //记录总数
        resultPage.setTotal((int) pageInfo.getTotal());
    }
}
